﻿// Spun AJAX Framework
// Copyright (C) 2008 Blake Hegerle
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace Formality
{
#if false
    public class Instrumentation : IDisposable
    {
        public Instrumentation(string Id)
        {
            this.Id = Id;
            Stopwatch = Stopwatch.StartNew();
        }

        public static void Report(bool Reset)
        {
            lock (Sync)
            {
                foreach (var I in InstrumentMap)
                    Console.WriteLine("{0} - {1} Calls in {2} - {3:0.00} ms/call",
                        I.Key, I.Value.Calls, I.Value.Duration, I.Value.MeanTime);

                if (Reset)
                    InstrumentMap = new Dictionary<string, Call>();
            }
        }

    #region IDisposable Members

        public void Dispose()
        {
            Stopwatch.Stop();

            lock (Sync)
            {
                Call Call;

                if (!InstrumentMap.TryGetValue(Id, out Call))
                    Call = new Call();

                Call.Add(Stopwatch.Elapsed);

                InstrumentMap[Id] = Call;
            }
        }

        #endregion

        private Stopwatch Stopwatch;
        private string Id;

        private static object Sync;
        private static Dictionary<string, Call> InstrumentMap;

        static Instrumentation()
        {
            Sync = new object();
            InstrumentMap = new Dictionary<string, Call>();
        }

        private struct Call
        {
            public TimeSpan Duration;
            public int Calls;

            public void Add(TimeSpan T) { Duration += T; Calls++; }

            public double MeanTime
            {
                get
                {
                    return Duration.TotalMilliseconds / (double)Calls;
                }
            }
        }
    }
#endif
}